home *** CD-ROM | disk | FTP | other *** search
/ Introduction to 3D Game …ogramming with DirectX 12 / Introduction-to-3D-Game-Programming-with-DirectX-12.ISO / Code.Textures / Chapter 13 The Compute Shader / SobelFilter / Shaders / Sobel.hlsl < prev    next >
Encoding:
Text File  |  2016-03-02  |  1.5 KB  |  44 lines

  1. //=============================================================================
  2. // Performs edge detection using Sobel operator.
  3. //=============================================================================
  4.  
  5. Texture2D gInput            : register(t0);
  6. RWTexture2D<float4> gOutput : register(u0);
  7.  
  8.  
  9. // Approximates luminance ("brightness") from an RGB value.  These weights are derived from
  10. // experiment based on eye sensitivity to different wavelengths of light.
  11. float CalcLuminance(float3 color)
  12. {
  13.     return dot(color, float3(0.299f, 0.587f, 0.114f));
  14. }
  15.  
  16. [numthreads(16, 16, 1)]
  17. void SobelCS(int3 dispatchThreadID : SV_DispatchThreadID)
  18. {
  19.     // Sample the pixels in the neighborhood of this pixel.
  20.     float4 c[3][3];
  21.     for(int i = 0; i < 3; ++i)
  22.     {
  23.         for(int j = 0; j < 3; ++j)
  24.         {
  25.             int2 xy = dispatchThreadID.xy + int2(-1 + j, -1 + i);
  26.             c[i][j] = gInput[xy]; 
  27.         }
  28.     }
  29.  
  30.     // For each color channel, estimate partial x derivative using Sobel scheme.
  31.     float4 Gx = -1.0f*c[0][0] - 2.0f*c[1][0] - 1.0f*c[2][0] + 1.0f*c[0][2] + 2.0f*c[1][2] + 1.0f*c[2][2];
  32.  
  33.     // For each color channel, estimate partial y derivative using Sobel scheme.
  34.     float4 Gy = -1.0f*c[2][0] - 2.0f*c[2][1] - 1.0f*c[2][1] + 1.0f*c[0][0] + 2.0f*c[0][1] + 1.0f*c[0][2];
  35.  
  36.     // Gradient is (Gx, Gy).  For each color channel, compute magnitude to get maximum rate of change.
  37.     float4 mag = sqrt(Gx*Gx + Gy*Gy);
  38.  
  39.     // Make edges black, and nonedges white.
  40.     mag = 1.0f - saturate(CalcLuminance(mag.rgb));
  41.  
  42.     gOutput[dispatchThreadID.xy] = mag;
  43. }
  44.